package com.sailing.study.bitOperation;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorBitOperation {
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // runState is stored in the high-order bits
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

    // Packing and unpacking ctl
    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static int ctlOf(int rs, int wc) { return rs | wc; }


    public static void main(String[] args) {
        System.out.println("RUNNING    = -1 << COUNT_BITS (29) --> "+ RUNNING);
        System.out.println("SHUTDOWN   =  0 << COUNT_BITS -->"+ SHUTDOWN);
        System.out.println("STOP       =  1 << COUNT_BITS -->" + STOP);
        System.out.println("TIDYING    =  2 << COUNT_BITS -->" + TIDYING);
        System.out.println("TERMINATED =  3 << COUNT_BITS -->" + TERMINATED);
        int c = new ThreadPoolExecutorBitOperation().ctl.get();
        int rs = runStateOf(c);
        System.out.println("runStateOf -> " + rs);
        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN && (rs >= STOP )) {
            System.out.println("rs >= SHUTDOWN true");
        }
    }
}
